package com.util.mail;

import java.io.FileNotFoundException;
import java.net.URL;
import java.io.InputStream;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Properties;

import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.util.configuration.ConfigurationParametersManager;
import com.util.configuration.MissingConfigurationParameterException;
import com.util.exceptions.InternalErrorException;

public class MailHelperPop implements MailHelper
{
    protected static final String CONFIGURATION_FILE =
        "MailConfiguration.properties"; 
	
	private final static Log log = LogFactory.getLog(MailHelper.class);
	
	private final static String SERVER_NAME_PROPERTY = null;
	private static String HOST_NAME_PROPERTY = null;
	private static int PORT_HOST_PROPERTY = 25;
	private static String AUTH_HOST_PROPERTY = "true";
	private static String USER_HOST_PROPERTY = null;
	private static String PSW_HOST_PROPERTY = null;
	
	private static MimeMessage message = null;
	private static Session session = null;
	private static boolean initializated = false;
	
	static{
		/* leer parametros de configuracion: 
         * host, puerto, usuario y psw cuenta, email administrador 
         */	
		try{
        	HOST_NAME_PROPERTY = ConfigurationParametersManager.getParameter("HOST_NAME_PROPERTY");
//		        	log.debug("HOST_NAME_PROPERTY="+HOST_NAME_PROPERTY);
			
			USER_HOST_PROPERTY = ConfigurationParametersManager.getParameter("USER_HOST_PROPERTY");
//					log.debug("USER_HOST_PROPERTY="+USER_HOST_PROPERTY);
			
			PSW_HOST_PROPERTY = ConfigurationParametersManager.getParameter("PSW_HOST_PROPERTY");								
//					log.debug("PSW_HOST_PROPERTY="+PSW_HOST_PROPERTY);
		}catch (Exception e){
			log.debug("EXCEPCION --> " + e.getMessage());
		}

		try{
			PORT_HOST_PROPERTY = Integer.parseInt(ConfigurationParametersManager.getParameter("PORT_HOST_PROPERTY"));
//					log.debug("PORT_HOST_PROPERTY="+PORT_HOST_PROPERTY);
		} catch (Exception e){
			log.warn(e.getMessage() + " Usando valor por defecto (25)");
		}		
	}
	
	public static void sendMail(String to, String textMessage)
	{
		try
		{
			if (initializated)
			{
				Transport transport = session.getTransport("smtp");
				transport.connect(HOST_NAME_PROPERTY, PORT_HOST_PROPERTY, USER_HOST_PROPERTY, PSW_HOST_PROPERTY);
				message.setText(textMessage,"ISO-8859-1");
				message.saveChanges();
				transport.sendMessage(message, message.getAllRecipients());
				transport.close();
			}
		}
		catch (Exception e) 
		{
			log.debug("EXCEPCION --> " + e.getMessage());
		}
	}
	
	public Collection<Message> getMails(boolean borrar)
		throws InternalErrorException{
		ArrayList rdo = new ArrayList();
		try 
		{
			//Create empty properties
			Properties props = new Properties();
			//Get session
			Session session = Session.getDefaultInstance(props, null);
			//Get the store
			Store store = session.getStore("pop3");
			store.connect(HOST_NAME_PROPERTY, PORT_HOST_PROPERTY, USER_HOST_PROPERTY, PSW_HOST_PROPERTY);
			//Get folder
			Folder folder;
			folder = store.getFolder("INBOX");
			if (borrar)
			{
				folder.open(Folder.READ_WRITE);
			}
			else
			{
				folder.open(Folder.READ_ONLY);
			}
			//Get all messages
			Message message[] = folder.getMessages();
			for (int i=0, n=message.length; i<n; i++) 
			{
				Message m = message[i];
				rdo.add(m);
				log.debug(i + ":\n\tFrom: " + m.getFrom()[0] + "\n" + m.getContent().toString());
				if (borrar)
				{
					m.setFlag(Flags.Flag.DELETED, true);
				}
			}
			folder.close(borrar);
			store.close();
			return rdo;
		} 
		catch (MessagingException e)
		{
			log.debug("EXCEPCION --> " + e.getMessage());
			throw new InternalErrorException(e);
		} 
		catch (IOException e) 
		{
			log.debug("EXCEPCION --> " + e.getMessage());
			throw new InternalErrorException(e);
		}

	}
	
}